package utils

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"strconv"
	"strings"
)

//接口使用Sign中间件进行接口加密时 获取参数
func Input(c *gin.Context) map[string]string{
	parms,_:= c.Get("parms")
	if parms==nil{
		//接口不带接口签名时获取参数
		method := c.Request.Method
		Parms:=make(map[string]string)
		if method == "GET" || method == "DELETE" {
			getParms := c.Request.URL.Query()
			for k,v:= range getParms{
				if len(v) > 1{
					Parms[k] = Strval(v)
				}else{
					Parms[k] = v[0]
				}
			}
		}else {
			contentType := c.Request.Header["Content-Type"]
			if contentType != nil {
				for _,v :=range contentType {
					//判断请求的contenType是否是 json
					if strings.Index(strings.ToLower(v),"json") != -1 {
						postParm:=make(map[string]interface{})
						postParms, _ := ioutil.ReadAll(c.Request.Body)
						json.Unmarshal([]byte(string(postParms)), &postParm)
						for k,v:=range postParm {
							Parms[k] = Strval(v)
						}
					}else{
						//对post参数进行初始化
						c.PostForm("")
						postForm := c.Request.Form
						for k,v:= range postForm{
							if len(v) > 1{
								Parms[k] = Strval(v)
							}else{
								Parms[k] = v[0]
							}
						}
					}
				}
			}else{
				return nil
			}

		}
		return Parms
	}
	return parms.(map[string]string)
}




func Strval(value interface{}) string {
	var key string
	if value == nil {
		return key
	}
	switch value.(type) {
	case float64:
		ft := value.(float64)
		key = strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		key = strconv.Itoa(it)
	case uint:
		it := value.(uint)
		key = strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		key = strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		key = strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		key = strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		key = strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		key = strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		key = strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		key = strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		key = strconv.FormatUint(it, 10)
	case string:
		key = value.(string)
	case []byte:
		key = string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		key = string(newValue)
	}
	return key
}